package mail.util;

import java.net.CookieManager;
import java.net.HttpCookie;
import java.util.List;
import java.util.Map;

import static com.han.http.util.Print.printlnErr;

/**
 * @Author: Hanjiafeng
 * @Date: 2019-1-22 11:44:00
 * @Desc: 处理cookie
 */
public class CookieParser {

    /**
     * 禁止初始化
     */
    private CookieParser() {
    }

    public static void parseList(Map<String, String> map, List<String> cookieList) {
        for (String cookie : cookieList) {
            parseString(map, cookie);
        }
    }

    private static void parseString(Map<String, String> map, String cookieStr) {
        String[] cookieArr = cookieStr.split(";");
        for (String cookie : cookieArr) {
            String[] keyValueArr = cookie.split("=");
            if (keyValueArr.length < 2) {
                continue;
            }
            try {
                String key = keyValueArr[0];
                //覆盖原先的value
                String value = keyValueArr[1];
                map.put(key, value);
            } catch (Exception e) {
                printlnErr(cookie);
                e.printStackTrace();
            }
        }
    }

    /**
     * 从CookieManager中获取指定名称的cookie
     *
     * @param cookieManager CookieManager
     * @param name          cookie名
     * @return cookie
     */
    public static String getSpecifiedCookie(CookieManager cookieManager, String name) {
        String value = "";
        List<HttpCookie> cookieList = cookieManager.getCookieStore().getCookies();
        for (HttpCookie httpCookie : cookieList) {
            String temp = httpCookie.getName();
            if (temp.contains(name)) {
                value = httpCookie.getValue();
                break;
            }
        }

        return value;
    }

    /**
     * 获取全部cookie
     *
     * @param cookieManager CookieManager
     * @return cookie
     */
    public static String getAllCookie(CookieManager cookieManager) {
        StringBuilder cookieSb = new StringBuilder();
        List<HttpCookie> cookieList = cookieManager.getCookieStore().getCookies();
        for (HttpCookie httpCookie : cookieList) {
            String name = httpCookie.getName();
            String value = httpCookie.getValue();
            cookieSb.append(name).append("=").append(value).append(";");
        }

        String cookie = "";
        if (cookieSb.length() != 0) {
            cookie = cookieSb.substring(0, cookieSb.length() - 1);
        }
        return cookie;
    }
}
